package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.ScenicComment;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.ScenicCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ScenicCommentRepository;
import cn.wolfcode.luowowo.comment.service.IScenicCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ScenicCommentServiceImpl implements IScenicCommentService {
    @Autowired
    private ScenicCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void commentAdd(ScenicComment scenicComment) {
        Date date = new Date();
        scenicComment.setCreateTime(date);
        if (scenicComment.getType()==ScenicComment.SCENIC_COMMENT_TYPE){
            ScenicComment commentParnt = repository.findById(scenicComment.getId()).get();
                commentParnt.getComments().add(scenicComment);
            repository.save(commentParnt);
        }else {
            repository.save(scenicComment);
        }
    }

    @Override
    public Page query(ScenicCommentQuery qo) {
        Query query = new Query();
        if (qo.getScenicId()!=-1) {
            query.addCriteria(Criteria.where("scenicId").is(qo.getScenicId()));
        }
        //总条数
        long count = template.count(query, ScenicComment.class);
        if (count==0) {
            return Page.empty();
        }
        //分页
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(pageRequest);
        List<ScenicComment> comments = template.find(query, ScenicComment.class);
        return new PageImpl(comments,pageRequest,count);
    }

    @Override
    public ScenicComment strategyThumbup(String id, Long userId) {
        //从mongoDB中拿取数据
        ScenicComment scenicComment = repository.findById(id).get();
        //获得该评论点赞人的集合
        List<Long> thumbuplist = scenicComment.getThumbuplist();
        System.out.println(thumbuplist);
        //判断当前点击用户是否在集合中
        if (thumbuplist.contains(userId)) {
            //成立 则是取消点赞
            thumbuplist.remove(userId);
            //点赞数-1
            scenicComment.setThumbupnum(scenicComment.getThumbupnum()-1);
        }else {
            //否则是点赞
            thumbuplist.add(userId);
            //点赞数+1
            scenicComment.setThumbupnum(scenicComment.getThumbupnum()+1);
        }
        this.commentAdd(scenicComment);
        return null;
    }
}
